package xps.and.uudaijia.userclient.view.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.bumptech.glide.Glide;
import com.jude.utils.JUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscriber;
import xps.and.uudaijia.userclient.App;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.data.baen.CodeBean;
import xps.and.uudaijia.userclient.data.baen.MapBean;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.service.RemoteService;
import xps.and.uudaijia.userclient.util.AppCommond;
import xps.and.uudaijia.userclient.util.CommonUtils;
import xps.and.uudaijia.userclient.util.GlobalPositionInfo;
import xps.and.uudaijia.userclient.util.TtsUtil;
import xps.and.uudaijia.userclient.view.base.BaseActivity;
import xps.and.uudaijia.userclient.view.fragment.MapFragment;
import xps.and.uudaijia.userclient.view.fragment.StateFragment;

public class MapActivity extends BaseActivity implements MapFragment.PinActivationListener, Handler.Callback {
    //状态页
    StateFragment stateFragment = new StateFragment();
    //地图页
    MapFragment mapViewFragment = new MapFragment();
    //到达预约地
    public String userid, qidian, OrderId, beginLng, beginAddress, orderStatus, driverHeadImg, driverName, endLng, endLat, endAddress, userPhone, remark, beginLat;
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.state_FtameLayout)
    FrameLayout stateFtameLayout;
    String orderType;
    private MyReceiver receiver = null;
    private long departureTime;
    private static final int msgKey1 = 1;
    String radius = "3000";
    String cishu = "1";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            GlobalPositionInfo globalPositionInfo = App.getInstance().getGloPosinfo();
            Intent intent = getIntent();
            beginLng = intent.getStringExtra("beginLng");
            beginLat = intent.getStringExtra("beginLat");
            if (!TextUtils.isEmpty(beginLng) && !TextUtils.isEmpty(beginLat)) {
                LatLng latLng = new LatLng(Double.parseDouble(beginLat), Double.parseDouble(beginLng));
                mapViewFragment.addMarker(latLng, R.drawable.s_s);
                mapViewFragment.moveCameraTo(latLng);
            }
            endLng = intent.getStringExtra("endLng");
            endLat = intent.getStringExtra("endLat");
            if (!TextUtils.isEmpty(endLng) && !TextUtils.isEmpty(endLat)) {
                LatLng locat_endPoint = new LatLng(Double.parseDouble(endLat), Double.parseDouble(endLng));
                mapViewFragment.addMarker(locat_endPoint, R.drawable.s_e);
            }
        }
    };

    @Override
    protected int getLayout() {
        return R.layout.activity_map;
    }

    @Override
    protected void setData() {
        mapViewFragment.setPinVisibility(View.GONE);
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        userid = intent.getStringExtra("userId");
        qidian = intent.getStringExtra("qidian");
        OrderId = intent.getStringExtra("OrderId");
        beginLng = intent.getStringExtra("beginLng");
        beginLat = intent.getStringExtra("beginLat");
        beginAddress = intent.getStringExtra("beginAddress");
        endLng = intent.getStringExtra("endLng");
        endLat = intent.getStringExtra("endLat");
        endAddress = intent.getStringExtra("endAddress");
        userPhone = intent.getStringExtra("userPhone");
        remark = intent.getStringExtra("remark");
        orderStatus = intent.getStringExtra("orderStatus");
        driverName = intent.getStringExtra("driverName");
        driverHeadImg = intent.getStringExtra("driverHeadImg");
        departureTime = Long.valueOf(intent.getStringExtra("departureTime"));
        orderType = intent.getStringExtra("orderType");
        Log.e("orderType", orderType);
        mapViewFragment.setPinActionListener(this);
        Bundle bundle = new Bundle();
        bundle.putString("remark", remark);
        bundle.putString("orderID", OrderId);
        bundle.putString("endAddress", endAddress);
        bundle.putString("endLat", endLat);
        bundle.putString("endLng", endLng);
        bundle.putString("beginAddress", beginAddress);
        bundle.putString("beginLng", beginLng);
        bundle.putString("userPhone", userPhone);
        bundle.putString("beginLat", beginLat);
        bundle.putString("driverName", driverName);
        bundle.putString("driverHeadImg", driverHeadImg);
        stateFragment.setArguments(bundle);
        CommonUtils.replaceFragment(R.id.state_FtameLayout, stateFragment, getSupportFragmentManager());
        CommonUtils.replaceFragment(R.id.container, mapViewFragment, getSupportFragmentManager());
        ButterKnife.bind(this);
        mHandler.sendEmptyMessageDelayed(0, 500);
        WebSocket();
        if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("xps.and.uudaijia.userclient.service.RemoteService");
        registerReceiver(receiver, filter);
        if (orderStatus.equals("0")) {
            actionbarTvTitle.setText("等待接单");
            YesNo();
            stateFtameLayout.setVisibility(View.GONE);
            UserNetWorks.getMapJingWeiDu(beginLat + "", beginLng + "", orderType, new Subscriber<MapBean>() {
                        @Override
                        public void onCompleted() {
                            Log.e("getMapJingWeiDu", "onCompleted");
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onNext(MapBean mapBean) {
                            if (mapBean.getReturn_code().equals("SUCCESS")) {
                                if (mapBean.getReturn_body() != null && mapBean.getReturn_body().size() > 0) {
                                    placeMarker(mapBean);
                                }
                            } else if (mapBean.getReturn_code().equals("FAIL")) {
                                JUtils.Toast(mapBean.getReturn_msg());
                            }
                        }
                    }
            );
        } else {
            actionbarTvTitle.setText("正在执行");
            stateFtameLayout.setVisibility(View.VISIBLE);
            ivMsg.setVisibility(View.GONE);
        }
    }

    void YesNo() {
        int mills = (int) (System.currentTimeMillis() / 1000 - departureTime);
        if (mills >= 600) {
            showCustomizeDialog();
            TimemHandler.removeCallbacksAndMessages(null);
        }
    }

    void placeMarker(MapBean mapBean) {
        for (int i = 0; i < mapBean.getReturn_body().size(); i++) {
            MapBean.ReturnBodyBean reb = mapBean.getReturn_body().get(i);
            Log.e("getMapJingWeiDu", reb.toString());
            MapBean.ReturnBodyBean.LatestLocationBean latestLocationBean = reb.getLatest_location();
            LatLng locat_endPointA = new LatLng(latestLocationBean.getLatitude(), latestLocationBean.getLongitude());
            mapViewFragment.addBQXMarker(locat_endPointA, reb.getEntity_desc().toString());
        }
    }

    @Override
    public void onPinMoved(final ArrayList<PoiInfo> p) {
        if (p == null || p.size() <= 0) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    @Override
    public void onPinMoveStart() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    void WebSocket() {
        Intent intent = new Intent(MapActivity.this, RemoteService.class);
        intent.putExtra("userId", userid);
        MapActivity.this.startService(intent);
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_tv_title, R.id.iv_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.actionbar_tv_title:
                break;
            case R.id.iv_msg:
                PopupMenu popupMenu = new PopupMenu(MapActivity.this, view);
                popupMenu.getMenuInflater().inflate(R.menu.activity_main_drawermap, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        int id = item.getItemId();
                        if (id == R.id.addfriend) {
                            Intent intent = new Intent(MapActivity.this, CancelActivity_v2.class);
                            intent.putExtra("panduan", "1");
                            intent.putExtra("orderID", OrderId);
                            startActivity(intent);
                        } else if (id == R.id.group) {
                            if (cishu.equals("1")) {
                                radius = "3000";
                                cishu = "2";
                                getReminder();
                            } else if (cishu.equals("2")) {
                                radius = "5000";
                                cishu = "3";
                                getReminder();
                            }
                        } else if (id == R.id.sao) {
                            showCYCDialogDH();
                        }
                        return true;
                    }
                });
                popupMenu.show();
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.equals(getClass().getSimpleName())) {
                unreg();
                finish();
                break;
            }
        }
    }

    void unreg() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    public class TimeThread extends Thread {
        @Override
        public void run() {
            super.run();
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = msgKey1;
                    TimemHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TimemHandler.removeCallbacksAndMessages(null);
        TimemHandler=null;
        unreg();

    }

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String count = bundle.getString("count");
            System.out.println("asdasdasdas" + count);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(count);
                if (jsonObject.getString("pushType").equals("scramble-order")) {
                    JUtils.Toast(jsonObject.getString("driverName") + "已接单");
                    stateFragment.yingcang.setVisibility(View.VISIBLE);
                    stateFragment.nameTextView.setText(jsonObject.getString("driverName"));
                    stateFragment.okTextView.setText(jsonObject.getString("startAddress"));
                    stateFragment.endTextView.setText(jsonObject.getString("endAddress"));
                    actionbarTvTitle.setText("已接单");
                    Glide.with(MapActivity.this).load(jsonObject.getString("driverHeadImg"))
                            .placeholder(R.mipmap.logo)
                            .bitmapTransform(new CropCircleTransformation(MapActivity.this))
                            .into(stateFragment.TXImageView);
                    ivMsg.setVisibility(View.GONE);
                    mapViewFragment.resetOverlay();
                    if (!TextUtils.isEmpty(beginLng) && !TextUtils.isEmpty(beginLat)) {
                        LatLng locat_endPoint = new LatLng(Double.parseDouble(beginLat), Double.parseDouble(beginLng));
                        mapViewFragment.addMarker(locat_endPoint, R.drawable.s_s);
                    }
                    if (!TextUtils.isEmpty(endLng) && !TextUtils.isEmpty(endLat)) {
                        LatLng locat_endPoint = new LatLng(Double.parseDouble(endLat), Double.parseDouble(endLng));
                        mapViewFragment.addMarker(locat_endPoint, R.drawable.s_e);
                    }
                } else if (jsonObject.getString("pushType").equals("BOD")) {
                    //JUtils.Toast(jsonObject.getString("pushMsg") + "");
                    TtsUtil.getInstance().startSpeaking(jsonObject.getString("pushMsg") + "");
                } else if (jsonObject.getString("pushType").equals("arrival-to-destination")) {
                    actionbarTvTitle.setText("司机到达预约地");
                    stateFragment.yingcang.setVisibility(View.VISIBLE);
                    stateFragment.nameTextView.setText(jsonObject.getString("driverName"));
                    stateFragment.okTextView.setText(jsonObject.getString("startAddress"));
                    stateFragment.endTextView.setText(jsonObject.getString("endAddress"));
                    actionbarTvTitle.setText("已接单");
                    Glide.with(MapActivity.this).load(jsonObject.getString("driverHeadImg"))
                            .placeholder(R.mipmap.logo)
                            .bitmapTransform(new CropCircleTransformation(MapActivity.this))
                            .into(stateFragment.TXImageView);
                    JUtils.Toast("到达预约地");
                    ivMsg.setVisibility(View.GONE);
                } else if (jsonObject.getString("pushType").equals("start-off")) {
                    JUtils.Toast("司机正在执行订单");
                    actionbarTvTitle.setText("正在行驶");
                    stateFragment.yingcang.setVisibility(View.VISIBLE);
                    stateFragment.nameTextView.setText(jsonObject.getString("driverName"));
                    stateFragment.okTextView.setText(jsonObject.getString("startAddress"));
                    stateFragment.endTextView.setText(jsonObject.getString("endAddress"));
                    actionbarTvTitle.setText("已接单");
                    Glide.with(MapActivity.this).load(jsonObject.getString("driverHeadImg"))
                            .placeholder(R.mipmap.logo)
                            .bitmapTransform(new CropCircleTransformation(MapActivity.this))
                            .into(stateFragment.TXImageView);
                    ivMsg.setVisibility(View.GONE);
                } else if (jsonObject.getString("pushType").equals("confirm-cost")) {
                    MapActivity.this.finish();
                    Intent intent1 = new Intent(MapActivity.this, PaymentActivity.class);
                    intent1.putExtra("orderID", OrderId);
                    intent1.putExtra("driverName", driverName);
                    intent1.putExtra("driverHeadImg", driverHeadImg);
                    intent1.putExtra("liebia", "1");
                    startActivity(intent1);
                    finish();
                } else if (jsonObject.getString("pushType").equals("cancel-order")) {
                    finish();
                } else if (jsonObject.getString("pushType").equals("settlement-express-train-order")) {
                    Intent DaiJiaIntent = new Intent(MapActivity.this, DaiJiaPayMentActivity.class);
                    DaiJiaIntent.putExtra("orderID", jsonObject.getString("orderId"));
                    startActivity(DaiJiaIntent);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    void getReminder() {
        UserNetWorks.getReminder(OrderId, radius, new Subscriber<CodeBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(CodeBean vehicleBean) {
                if (vehicleBean.getReturn_code().equals("SUCCESS")) {
                    showCYCDialog();
                } else if (vehicleBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(vehicleBean.getReturn_msg());
                }
            }
        });
    }

    public void showCustomizeDialog() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MapActivity.this);
        final View dialogView = LayoutInflater.from(MapActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("此单长时间没有司机接单,为保障您出行方便请取消或重新发单.");
        customizeDialog.setTitle("温馨提示");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("联系客服",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent phoneIntent = new Intent("android.intent.action.CALL",
                                Uri.parse("tel: 022-58397002"));
                        startActivity(phoneIntent);
                    }
                });
        customizeDialog.setNegativeButton("知道了",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PopupMenu popupMenu = new PopupMenu(MapActivity.this, dialogView);
                        popupMenu.getMenuInflater().inflate(R.menu.activity_main_drawermap, popupMenu.getMenu());
                        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            public boolean onMenuItemClick(MenuItem item) {
                                int id = item.getItemId();
                                if (id == R.id.addfriend) {
                                    Intent intent = new Intent(MapActivity.this, CancelActivity_v2.class);
                                    intent.putExtra("orderID", OrderId);
                                    intent.putExtra("panduan", "1");
                                    startActivity(intent);
                                } else if (id == R.id.group) {
                                    getReminder();
                                } else if (id == R.id.sao) {
                                    showCYCDialogDH();
                                }
                                return true;
                            }
                        });
                        popupMenu.show();
                    }
                });
       /* customizeDialog.setCancelable(false);*/
        customizeDialog.show();
    }

    public void showCYCDialog() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MapActivity.this);
        final View dialogView = LayoutInflater.from(MapActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("催单成功,如长时间没有司机接单,请拨打客服电话!");
        customizeDialog.setTitle("温馨提示");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("拨打客服",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent phoneIntent = new Intent("android.intent.action.CALL",
                                Uri.parse("tel: 022-58397002"));
                        startActivity(phoneIntent);
                    }
                });
        customizeDialog.setNegativeButton("知道了",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
       /* customizeDialog.setCancelable(false);*/
        customizeDialog.show();
    }


    private Handler TimemHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey1:
                    xiaohui();
                    break;
                default:
                    break;
            }
        }
    };

    void xiaohui() {
        int mills = (int) (System.currentTimeMillis() / 1000 - departureTime);
        if (mills >= 2) {
            showCustomizeDialog();
            TimemHandler.removeCallbacksAndMessages(null);
        }
    }

    public void showCYCDialogDH() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MapActivity.this);
        final View dialogView = LayoutInflater.from(MapActivity.this)
                .inflate(R.layout.dialog_dianhua, null);
        TextView textView = (TextView) dialogView.findViewById(R.id.edit_text);
        textView.setText("022-58397002");
        customizeDialog.setTitle("客服电话");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent phoneIntent = new Intent("android.intent.action.CALL",
                                Uri.parse("tel: 022-58397002"));
                        startActivity(phoneIntent);
                    }
                });
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        customizeDialog.show();
    }
}